package com.sduept.nwld.dataserver.controller.equipment.assessment;

import com.sduept.bigdata.equipment.assessment.model.hiddendanger.knowledgebase.KnowledgeBase;
import com.sduept.bigdata.equipment.assessment.model.hiddendanger.knowledgebase.KnowledgeQueryParamModel;
import com.sduept.bigdata.equipment.assessment.model.inspection.InspectionExpert;
import com.sduept.bigdata.equipment.assessment.model.standarddict.HiddenDangerLevel;
import com.sduept.bigdata.equipment.assessment.model.standarddict.HiddenDangerQuesType;
import com.sduept.bigdata.equipment.assessment.model.standarddict.HiddenDangerReasonType;
import com.sduept.bigdata.equipment.assessment.model.standarddict.HiddenDangerSource;
import com.sduept.bigdata.equipment.assessment.service.HiddenDangerKnowledageBaseService;
import com.sduept.bigdata.equipment.assessment.service.InspectionExpertService;
import com.sduept.bigdata.web.jsf.controller.AbstractController;
import com.sduept.core.entity.AbstractStandardDict;
import com.sduept.core.service.StandardDictService;
import com.sduept.utils.PingYinUtil;
import org.primefaces.PrimeFaces;
import org.primefaces.event.SelectEvent;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;
import javax.faces.view.ViewScoped;
import javax.inject.Named;
import java.util.*;
import java.util.Map.Entry;
import java.util.stream.Collectors;

@Named
@ViewScoped
public class KnowledgeBaseController extends AbstractController {


	/**
	 * 
	 */
	private static final long serialVersionUID = -4777409575022542302L;


	@Autowired
	private HiddenDangerKnowledageBaseService hdkbService;
	@Autowired
	private InspectionExpertService expertService ;
    @Autowired
    private StandardDictService dictService;
	
	
	private List<String> quesList ; // 问题归类
	private List<String> reasonList ;//原因归类
	private List<String> gradeList ; // 隐患等级
    private List<String> sourceList; // 隐患来源

	private List<KnowledgeBase> kbs;
	private KnowledgeBase selectKb = null;
	private KnowledgeBase created = null;
	private KnowledgeQueryParamModel queryParam; 

	@PostConstruct
	private void init() {
		try {
			kbs = hdkbService.findAllKnowledgeBases();
			quesList = getStringList(HiddenDangerQuesType.class);
			gradeList = getStringList(HiddenDangerLevel.class);
			reasonList = getStringList(HiddenDangerReasonType.class);
			sourceList=getStringList(HiddenDangerSource.class);
			queryParam=new KnowledgeQueryParamModel();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	


   /**
        * 原因归类和问题归类的关联
        * @throws Exception 
    */
   public void association() throws Exception {
	   //存放问题归类  及对应的原因归类
	   Map<String, Map<String,Integer>> ass = new HashMap<String, Map<String,Integer>>();
	   List<KnowledgeBase> ks = hdkbService.findAllKnowledgeBases();
	   for (KnowledgeBase k : ks) {
		   if(!ass.containsKey(k.getHiddenDangerQuesClass()) && k.getHiddenDangerQuesClass()!=null) {
			   Map<String,Integer> values = new HashMap<String, Integer>();
			   List<KnowledgeBase>  lists =   hdkbService.findKnowledgeBasesByQuesClass(k.getHiddenDangerQuesClass());
		         for (KnowledgeBase k_ques : lists) {
		        	 String reasonClass = k_ques.getHiddenDangerReasonClass();
		        	 if(values.containsKey(reasonClass)) {
		        		 Integer v = values.get(reasonClass);
		        		 values.put(reasonClass, v+1);
		        	 }else if(reasonClass!=null){
		        		 values.put(reasonClass, 1);
		        	 }
				}
		         ass.put(k.getHiddenDangerQuesClass(), values);
		   } 
	}
	   Map<String,Integer> reasonMap = ass.get(created.getHiddenDangerQuesClass());
	   if(reasonMap!=null) {
		   List<Entry<String, Integer>> list = getSortList(reasonMap);
	       String reasonClass = list.get(list.size()-1).getKey();
	     created.setHiddenDangerReasonClass(reasonClass);  
	   }
	  
	}
      /**
       * 专家与管辖专业、隐患来源的关联显示
       * @throws Exception
       */
     public void associationExpert() throws Exception {
    	 InspectionExpert  expert = expertService.findByName(created.getExpertName());
    	 List<KnowledgeBase> lists = hdkbService.findKnowledgeBasesByExpertCode(expert.getCode());
    	  Map<String,Integer> values = new HashMap<String, Integer>();
    	  Map<String,Integer> sourceValues = new HashMap<String, Integer>();
    	 if(lists.size()>0) {
    		 for (KnowledgeBase knowledgeBase : lists) {
    			 String jSpecialty = knowledgeBase.getjSpecialty();
    			 String source = knowledgeBase.getHiddenDangerSources();
	        	 if(values.containsKey(jSpecialty)) {
	        		 Integer v = values.get(jSpecialty);
	        		 values.put(jSpecialty, v+1);
	        	 }else if(jSpecialty!=null){
	        		 values.put(jSpecialty, 1);
	        	 }
	        	 if(sourceValues.containsKey(source)) {
	        		 Integer v = sourceValues.get(source);
	        		 sourceValues.put(source, v+1);
	        	 }else if(source!=null){
	        		 sourceValues.put(source, 1);
	        	 }
			}
    		 List<Entry<String,Integer>> jSpecialtyList = getSortList(values);
    		  if(jSpecialtyList.size()>0) {
    			  String js = jSpecialtyList.get(jSpecialtyList.size()-1).getKey();
    	    		 created.setjSpecialty(js); 
    		  }
    		  List<Entry<String,Integer>> sourceList = getSortList(sourceValues);
    		  if(sourceList.size()>0) {
    			  String s = sourceList.get(sourceList.size()-1).getKey();
    	    		 created.setHiddenDangerSources(s); 
    		  }
    	 }
     }
   
     /**
      * 对map的排序
      * @param values
      * @return
      */
     private List<Entry<String, Integer>> getSortList(Map<String, Integer> values) {
    	 List<Entry<String, Integer>> list = values.entrySet().stream()
		    	 .sorted((entry1,entry2)->entry1.getValue()
		    			 .compareTo(entry2.getValue()))
		    	 .collect(Collectors.toList());
		return list;
	}


	
   
   /**
    * 管辖专业
    * @param query
    * @return
    */
    public List<String>  completeHiddenDangerJSpecialty(String query) {
    	 List<String> jSpecialtyList = new ArrayList<String>(); // 管辖专业
    	 for (KnowledgeBase k_ques : kbs) {
        	    if(!jSpecialtyList.contains(k_ques.getjSpecialty()) && k_ques.getjSpecialty()!=null) {
        	    	jSpecialtyList.add(k_ques.getjSpecialty());
    	    }
 		}
    	return  jSpecialtyList;
    }

    public void resetQuery() {	
    	init();
		selectKb = null;
		created=null;
	}

	
	/**
	 * 修改
	 */
	public void update() {
		try {
			if (selectKb != null) {
				hdkbService.createOrUpdateKnowledgeBase(selectKb);
				addSuccessMessage("编辑成功！");
			}
		} catch (Exception e) {
			addSuccessMessage("编辑失败！");
			e.printStackTrace();
		}
	}

	/**
	 * 新
	 */
	public void create() {
		created = new KnowledgeBase();
		created.setExpertName(getCurrentUser().getName());
		created.setExpertCode(getCurrentUser().getCode());
	}
	/**
	 * 专家在输入框的显示
	 * @param query
	 * @return
	 */
	public List<String> complateExpert(String query) {
		List<InspectionExpert>	selectExperts = expertService.findAll();
		Set<String> names = new LinkedHashSet<String>();
		for (InspectionExpert expert : selectExperts) {
			String nameHead = PingYinUtil.getPingYinHeader(expert.getName());
			if (nameHead.toLowerCase().contains(query)) {
				names.add(expert.getName());
			}
			if (expert.getName().contains(query)) {
				names.add(expert.getName());
			}
		}
		return new ArrayList<String>(names);
	}
	
	/**
	 * 隐患等级
	 * @param query
	 * @return
	 * @throws Exception 
	 */
	public List<String> completeHiddenDangerGrade(String query) throws Exception {
		List<String> results = new ArrayList<String>();	
		for (String s : gradeList) {
			if (s.contains(query)) {
				results.add(s);
			}
		}
		return results;
	}
	
	
	
	@SuppressWarnings("unchecked")
	private <T> List<String> getStringList(Class<T> T) throws Exception {
		List<String> results = new ArrayList<String>();
		List<AbstractStandardDict> list = (List<AbstractStandardDict>) dictService.findAll(Class.forName(T.getName()));
		for (AbstractStandardDict s : list) {
			results.add(s.getName());
		}
		return results;
	}


	/**
	 * 问题归类
	 * @param query
	 * @return
	 * @throws Exception 
	 */
	public List<String> completeHiddenDangerQuesClass(String query) throws Exception {
		List<String> results = new ArrayList<String>();		
		for (String s : quesList) {
			if (s.contains(query)) {
				results.add(s);
			}
		}
		return results;
	}
	/**
     * 原因归类
     * @param query
     * @return
	 * @throws Exception 
     */
   public List<String>  completeHiddenDangerReasonClass(String query) throws Exception {
	   List<String> results = new ArrayList<String>();	  
		for (String s : reasonList) {
			if (s.contains(query)) {
				results.add(s);
			}
		}
		return results;
	   
   }
	/**
	 * 隐患来源
	 * @param query
	 * @return
	 */
	public List<String> completeHiddenDangerSources(String query) {
		List<String> results = new ArrayList<String>();
		for (String s : sourceList) {
			if (s.contains(query)) {
				results.add(s);
			}
		}
		return results;
	}
	/**
	 * opendialog保存按钮触发事件
	 */
	public void saveNew() {
		try {
			if (created != null) {
				InspectionExpert expert =expertService.findByName(created.getExpertName());
				created.setExpertCode(expert.getCode());
				created.setCreatedTime(new Date());
				created = hdkbService.createOrUpdateKnowledgeBase(created);
			}
			created = null;
			kbs = hdkbService.findAllKnowledgeBases();
			addSuccessMessage("保存成功");
		} catch (Exception e) {
			addErrorMessage("保存失败！");
			e.printStackTrace();
		}
	}
	
	
	public void chooseKnowledge() {
        Map<String,Object> options = new HashMap<String, Object>();
        options.put("resizable", true);
        options.put("draggable", true);
        options.put("modal", true);
        options.put("reflow", true);//堆叠
        options.put("height", 600);
        options.put("contentWidth", 1100);
        options.put("contentHeight", 600);
        Map<String,List<String>> params = new HashMap<>();
        //openDialog("/ui/common/knowledgebase_selector_single.xhtml",  params,options);
        PrimeFaces.current().dialog().openDynamic("/ui/common/knowledgebase_selector_single.xhtml",  options,params);
        
	}
	
	/**
	 * 删除方法
	 */
	public void delete() {
		try {
			if (selectKb != null) {
				hdkbService.deleteKnowledgeBase(selectKb);
				kbs.remove(selectKb);
				selectKb= null;
				addSuccessMessage("删除成功！");
			} else {
				addErrorMessage("请选择一条数据进行删除！");
			}
		} catch (Exception e) {
			addErrorMessage("删除失败！");
			e.printStackTrace();
		}
	}

	public void RowSelect(SelectEvent event) {
		selectKb = (KnowledgeBase) event.getObject();
	}

	/**
	 * 页面查询方法
	 */
	public void query() {		
		try {
			kbs=hdkbService.findByCondition(queryParam.getCondition());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	public HiddenDangerKnowledageBaseService getHdkbService() {
		return hdkbService;
	}

	public void setHdkbService(HiddenDangerKnowledageBaseService hdkbService) {
		this.hdkbService = hdkbService;
	}

	public List<KnowledgeBase> getKbs() {
		return kbs;
	}

	public void setKbs(List<KnowledgeBase> kbs) {
		this.kbs = kbs;
	}

	public KnowledgeBase getSelectKb() {
		return selectKb;
	}

	public void setSelectKb(KnowledgeBase selectKb) {
		this.selectKb = selectKb;
	}

	public KnowledgeBase getCreated() {
		return created;
	}

	public void setCreated(KnowledgeBase created) {
		this.created = created;
	}


	public List<String> getQuesList() {
		return quesList;
	}


	public void setQuesList(List<String> quesList) {
		this.quesList = quesList;
	}


	public List<String> getReasonList() {
		return reasonList;
	}


	public void setReasonList(List<String> reasonList) {
		this.reasonList = reasonList;
	}


	public List<String> getGradeList() {
		return gradeList;
	}


	public void setGradeList(List<String> gradeList) {
		this.gradeList = gradeList;
	}


	public List<String> getSourceList() {
		return sourceList;
	}


	public void setSourceList(List<String> sourceList) {
		this.sourceList = sourceList;
	}


	

	

	public KnowledgeQueryParamModel getQueryParam() {
		return queryParam;
	}



	public void setQueryParam(KnowledgeQueryParamModel queryParam) {
		this.queryParam = queryParam;
	}  
	
	
}
